package com.ganbo.thread;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 面试题：使用多线程顺序打印：A，B，C
 */
public class ThreadSortPrint {

    private Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();


    private static int number = 1;

    public void printA() {
        while (true) {
            lock.lock();
            try {
                if (number == 1) {
                    System.out.println(Thread.currentThread().getName() + "====> A");
                    ++number;
                    conditionB.signal();
                    conditionA.await();
                }
            } catch (Exception e) {

            } finally {
                lock.unlock();
            }
        }
    }


    public void printB() {
        while (true) {
            lock.lock();
            try {
                if (number == 2) {
                    System.out.println(Thread.currentThread().getName() + "====> B");
                    ++number;
                    conditionC.signal();
                    conditionB.await();
                }
            } catch (Exception e) {

            } finally {
                lock.unlock();
            }
        }
    }

    public void printC() {
        while (true) {
            lock.lock();
            try {
                if (number == 3) {
                    System.out.println(Thread.currentThread().getName() + "====> C");
                    number = 1;
                    conditionA.signal();
                    conditionC.await();
                }
            } catch (Exception e) {

            } finally {
                lock.unlock();
            }
        }
    }


    public static void main(String[] args) {
        final ThreadSortPrint t = new ThreadSortPrint();

        new Thread(new Runnable() {
            public void run() {
                t.printA();
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                t.printB();
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                t.printC();
            }
        }).start();
    }

}
